import java.util.HashMap;
import java.util.Map;

public class Solution889 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public TreeNode constructFromPrePost(int[] preorder, int[] postorder) {
        Map<Integer,Integer> map=new HashMap<>();
        for (int i=0;i<postorder.length;i++){
            map.put(postorder[i],i);
        }
        return dfs(preorder,0,preorder.length-1,0,postorder.length-1,map);
    }

    private TreeNode dfs(int[] preorder, int s1, int e1, int s2, int e2, Map<Integer,Integer> map) {
        if (s1>e1){
            return null;
        }
        TreeNode treeNode=new TreeNode(preorder[s1]);
        if (s1==e1){
            return treeNode;
        }
        int t=map.get(preorder[s1+1]);
        treeNode.left=dfs(preorder,s1+1,t-s2+s1+1,s2,t,map);
        treeNode.right=dfs(preorder,e1+t+2-e2,e1,t+1,e2-1,map);
        return treeNode;
    }

    public static void main(String[] args) {
        System.out.println(new Solution889().constructFromPrePost(new int[]{1,2,4,5,3,6,7},new int[]{4,5,2,6,7,3,1}).right.val);
    }
}
